package com.wash.shoes.controller.pc;

import com.alibaba.fastjson.JSONObject;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonCancelOrderV1.CommonOrderCancelRequest;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.EcapV1OrdersCancelLopRequest;
import com.lop.open.api.sdk.response.ECAP.EcapV1OrdersCancelLopResponse;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.wash.shoes.common.enums.OrderStatusEnum;
import com.wash.shoes.common.property.JdProperty;
import com.wash.shoes.domain.jd.JdOrderService;
import com.wash.shoes.domain.mtbusy.MtUpdateFulFillInfo;
import com.wash.shoes.entity.JdCallRecordPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.service.JdCallRecordService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @author wangxy
 * @date 2024/9/24 21:23
 */
@Api(tags = {"PC-商家主动取消订单"})
@RestController
@RequestMapping({"/merchantCancelOrder", "/dev-api/merchantCancelOrder"})
public class MtMerchantCancelOrder {

    private static final Logger log = LoggerFactory.getLogger("mt-record");
    private static final Set<String> MANAGER_ROLES = new HashSet<>(Arrays.asList("admin", "shopowner"));

    /**
     * 订单服务
     */
    @Autowired
    OrderService orderService;

    /**
     * 权限服务
     */
    @Autowired
    private SysPermissionService permissionService;

    /**
     * 订单物流服务
     */
    @Autowired
    OrderTransportService orderTransportService;

    /**
     * 美团更新服务
     */
    @Autowired
    MtUpdateFulFillInfo mtUpdateFulFillInfo;

    /**
     * 京东查询参数
     */
    @Autowired
    JdProperty jdProperty;


    @Autowired
    JdCallRecordService jdCallRecordService;

    @Autowired
    JdOrderService jdOrderService;

    @ApiOperation("商家通过订单id进行改约")
    @GetMapping("/cancelOrderByOrderId")
    public R<String> cancelOrderByOrderOn(String orderId) {

        // 校验登录人角色
        SysUser user = SecurityUtils.getLoginUser().getUser();

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        log.info("美团取消,角色查询 {}", String.join(",", roles));

        // 判断用户是否有管理权限
        boolean hasManagerRole = roles.stream().anyMatch(MANAGER_ROLES::contains);

        // 如果没有权限，返回失败信息
        if (!hasManagerRole) {
            return R.fail("你没有权限操作,请联系店长或者超级管理员!!");
        }

        //判断订单状态
        OrderPo orderPo = orderService.getById(orderId);
        if (Objects.isNull(orderPo)) {
            return R.fail("订单不存在!!");
        }

        //目前这个商家取消接口给美团用的，以后有了抖音、小程序在抽取出来
        if (!StringUtils.equals(orderPo.getComeFrom(), "2")) {
            return R.fail("订单来源渠道不正确，不能被取消!!");
        }

        //判断订单状态，只有订单是取鞋中才能取消
        if (!Objects.equals(orderPo.getStatus(), OrderStatusEnum.PICK_UP_SHOES.getStatus())) {
            return R.fail("订单状态不正确，不能被取消!!");
        }
        OrderTransportPo orderTransportPo = orderTransportService.getOneByOrderId(orderId);
        //京东物流状态判断
        String jdStatus = jdOrderService.jdLogisticsStatus(orderTransportPo);

        log.info("美团取消京东物流状态为 {}", jdStatus);

        if (!StringUtils.equals(orderTransportPo.getType(), "取鞋")) {
            return R.fail("物流状态不正确，不能取消!!");
        }

        if (StringUtils.equals(jdStatus, "420")) {
            return R.fail("物流已经揽收，不能被取消!!");
        }
        //调用美团取消
        mtUpdateFulFillInfo.shopCancelOrder(orderId);
        // 调用京东取消物流信息
        jdCancelLogistics(orderPo, orderTransportPo);
        return R.ok();
    }

    /**
     * 调用京东取消物流信息
     *
     * @param orderPo
     * @param orderTransportPo
     */
    private void jdCancelLogistics(OrderPo orderPo, OrderTransportPo orderTransportPo) {
        EcapV1OrdersCancelLopRequest cancelLopRequest = new EcapV1OrdersCancelLopRequest();
        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        cancelLopRequest.addLopPlugin(lopPlugin);

        CommonOrderCancelRequest commonOrderCancelRequest = new CommonOrderCancelRequest();
        commonOrderCancelRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonOrderCancelRequest.setCancelReason("用户取消");
        // 取消原因编码；枚举值：1-用户发起取消；2-超时未支付
        commonOrderCancelRequest.setCancelReasonCode("1");
        commonOrderCancelRequest.setCustomerCode(jdProperty.getCustomerCode());
        commonOrderCancelRequest.setWaybillCode(orderTransportPo.getWayBillCode());

        cancelLopRequest.setRequest(commonOrderCancelRequest);

        try {
            EcapV1OrdersCancelLopResponse response = client.execute(cancelLopRequest);
            log.info("EcapV1OrdersCancelLopResponse is request:[{}]  response:[{}]", JSONObject.toJSONString(commonOrderCancelRequest), JSONObject.toJSONString(response));
            // 调用的记录
            JdCallRecordPo jdCallRecordPo = new JdCallRecordPo();
            jdCallRecordPo.setWayBillCode(orderTransportPo.getWayBillCode());
            jdCallRecordPo.setOrderId(orderPo.getId());
            jdCallRecordPo.setOrderNo(orderPo.getOrderNo());
            jdCallRecordPo.setRequestInfo(JSONObject.toJSONString(commonOrderCancelRequest));
            jdCallRecordPo.setRespondInfo(JSONObject.toJSONString(response));
            jdCallRecordPo.setRequestId(response.getResult().getRequestId());
            jdCallRecordService.save(jdCallRecordPo);
            if (response.getResult().getCode() != 0) {
                log.error("取消jd的订单信息失败 jdCallRecordPo id 是{}", jdCallRecordPo.getId());
                throw new RuntimeException("订单取消失败,请联系管理员: " + orderTransportPo.getWayBillCode());
            }
            // 更新订单为取消
            orderPo.setStatus(OrderStatusEnum.CANCEL.getStatus());
            orderService.updateById(orderPo);
            // jd物流的信息,更新为取消
            orderTransportPo.setStatus("690");
            orderTransportService.updateById(orderTransportPo);

            log.info("商家取消订单成功 {}", orderPo.getOrderNo());


        } catch (LopException e) {
            throw new RuntimeException(e);
        }
    }


}
